<template>
  <div class="submission-form">
    <div class="page-header">
      <h1 class="page-title">{{ $t('assets.homework.submissionTitle') }}</h1>
    </div>

    <!-- 待提交作业列表 -->
    <div v-if="pendingHomework.length > 0" class="homework-list">
      <el-card v-for="homework in pendingHomework" :key="homework.id" class="homework-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div class="homework-info">
              <h3 class="homework-title">{{ homework.title }}</h3>
              <div class="homework-meta">
                <el-tag :type="getSubjectType(homework.subject)" size="small">
                  {{ getSubjectName(homework.subject) }}
                </el-tag>
                <el-tag type="warning" size="small">
                  {{ $t('assets.homework.dueDate') }}: {{ formatDate(homework.dueDate) }}
                </el-tag>
              </div>
            </div>
            <div class="homework-actions">
              <el-button type="primary" :icon="Camera" @click="openCamera(homework)">
                {{ $t('assets.homework.takePhoto') }}
              </el-button>
              <el-button :icon="View" @click="viewHomeworkDetail(homework)">
                {{ $t('assets.homework.viewDetail') }}
              </el-button>
            </div>
          </div>
        </template>

        <div class="homework-content">
          <p class="homework-desc">{{ homework.description }}</p>
        </div>

        <!-- 已拍摄的图片预览 -->
        <div v-if="homework.photos && homework.photos.length > 0" class="photos-preview">
          <h4>{{ $t('assets.homework.capturedPhotos') }}</h4>
          <div class="photos-grid">
            <div v-for="photo in homework.photos" :key="photo.id" class="photo-item">
              <img :src="photo.thumbnail" :alt="photo.fileName" class="photo-thumbnail" />
              <div class="photo-actions">
                <el-button size="small" @click="viewPhoto(photo)">{{ $t('common.view') }}</el-button>
                <el-button size="small" type="danger" @click="deletePhoto(homework.id, photo.id)">{{ $t('common.delete') }}</el-button>
              </div>
            </div>
          </div>
          <div class="submit-section">
            <el-button type="success" @click="submitHomework(homework)">
              {{ $t('assets.homework.submitHomework') }}
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <el-card v-else>
      <div class="empty-state">
        <el-empty :description="$t('assets.homework.noPendingHomework')">
          <el-button type="primary" @click="goToAllHomework">{{ $t('assets.homework.viewAllHomework') }}</el-button>
        </el-empty>
      </div>
    </el-card>

    <!-- 摄像头模态框 -->
    <el-dialog v-model="showCameraModal" :title="$t('assets.homework.takePhoto')" width="80%" :before-close="closeCameraModal">
      <CameraCapture
        @close="closeCameraModal"
        @photo-captured="handlePhotoCapture"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Camera, View } from '@element-plus/icons-vue'
import { t as $t } from '@/plugins/simpleI18n'
import { photosStorage, type PhotoData } from '@/utils/photosDB'
import CameraCapture from '@/components/shared/Camera/CameraCapture.vue'

const router = useRouter()

// 响应式数据
const showCameraModal = ref(false)
const currentHomework = ref<any>(null)

// 作业数据接口
interface HomeworkPhoto {
  id: string
  fileName: string
  thumbnail: string
  fullImage: string
  uploadTime: string
}

interface PendingHomework {
  id: number
  title: string
  description: string
  subject: string
  dueDate: Date
  photos?: HomeworkPhoto[]
}

// 待提交作业数据
const pendingHomework = ref<PendingHomework[]>([
  {
    id: 1,
    title: '数学作业 - 第三章练习',
    description: '完成教材第三章所有练习题，包括应用题和计算题',
    subject: 'math',
    dueDate: new Date('2025-08-05'),
    photos: []
  },
  {
    id: 2,
    title: '语文作业 - 古诗词背诵',
    description: '背诵并默写指定的古诗词，注意字体工整',
    subject: 'chinese',
    dueDate: new Date('2025-08-03'),
    photos: []
  },
  {
    id: 3,
    title: '英语作业 - 单词练习',
    description: '完成Unit 5的单词练习和短语搭配',
    subject: 'english',
    dueDate: new Date('2025-08-04'),
    photos: []
  }
])

// 方法
const getSubjectName = (subject: string) => {
  const subjectMap: Record<string, string> = {
    math: $t('assets.subjects.math'),
    chinese: $t('assets.subjects.chinese'),
    english: $t('assets.subjects.english'),
    other: $t('assets.subjects.other')
  }
  return subjectMap[subject] || subject
}

const getSubjectType = (subject: string) => {
  const typeMap: Record<string, string> = {
    math: 'primary',
    chinese: 'success',
    english: 'warning',
    other: 'info'
  }
  return typeMap[subject] || 'info'
}

const formatDate = (date: Date) => {
  return date.toLocaleDateString('zh-CN')
}

const openCamera = (homework: PendingHomework) => {
  currentHomework.value = homework
  showCameraModal.value = true
}

const closeCameraModal = () => {
  showCameraModal.value = false
  currentHomework.value = null
}

const handlePhotoCapture = async (photoData: PhotoData) => {
  if (!currentHomework.value) return

  try {
    // 为作业图片添加特殊标记
    const homeworkPhoto = {
      ...photoData,
      category: 'homework-submission',
      homeworkId: currentHomework.value.id,
      uploadTime: new Date().toISOString()
    }

    await photosStorage.savePhoto(homeworkPhoto)

    // 更新当前作业的图片列表
    const homework = pendingHomework.value.find(h => h.id === currentHomework.value!.id)
    if (homework) {
      if (!homework.photos) homework.photos = []
      homework.photos.push({
        id: photoData.id,
        fileName: photoData.fileName || 'homework-photo.jpg',
        thumbnail: photoData.thumbnail,
        fullImage: photoData.fullImage,
        uploadTime: homeworkPhoto.uploadTime
      })
    }

    ElMessage.success($t('assets.homework.photoSavedSuccess'))
    closeCameraModal()
  } catch (error) {
    console.error('保存作业图片失败:', error)
    ElMessage.error($t('assets.homework.photoSaveError'))
  }
}

const viewPhoto = (photo: HomeworkPhoto) => {
  // 跳转到图片预览页面
  router.push({
    name: 'photo-preview',
    query: { photoId: photo.id }
  })
}

const deletePhoto = async (homeworkId: number, photoId: string) => {
  try {
    await ElMessageBox.confirm(
      $t('assets.homework.confirmDeletePhoto'),
      $t('common.warning'),
      {
        confirmButtonText: $t('common.confirm'),
        cancelButtonText: $t('common.cancel'),
        type: 'warning',
      }
    )

    await photosStorage.deletePhoto(photoId)

    // 从作业的图片列表中移除
    const homework = pendingHomework.value.find(h => h.id === homeworkId)
    if (homework && homework.photos) {
      homework.photos = homework.photos.filter(p => p.id !== photoId)
    }

    ElMessage.success($t('common.deleteSuccess'))
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除图片失败:', error)
      ElMessage.error($t('common.deleteError'))
    }
  }
}

const submitHomework = async (homework: PendingHomework) => {
  if (!homework.photos || homework.photos.length === 0) {
    ElMessage.warning($t('assets.homework.pleaseAddPhotos'))
    return
  }

  try {
    await ElMessageBox.confirm(
      $t('assets.homework.confirmSubmitHomework'),
      $t('common.confirm'),
      {
        confirmButtonText: $t('common.submit'),
        cancelButtonText: $t('common.cancel'),
        type: 'info',
      }
    )

    // 这里可以添加提交到服务器的逻辑
    console.log('提交作业:', homework)

    // 从待提交列表中移除
    pendingHomework.value = pendingHomework.value.filter(h => h.id !== homework.id)

    ElMessage.success($t('assets.homework.submitSuccess'))
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交作业失败:', error)
      ElMessage.error($t('assets.homework.submitError'))
    }
  }
}

const viewHomeworkDetail = (homework: PendingHomework) => {
  router.push(`/student/learning-tasks/detail/${homework.id}`)
}

const goToAllHomework = () => {
  router.push('/student/learning-tasks')
}

onMounted(() => {
  console.log('作业提交页面加载完成')
})
</script>

<style scoped>
.submission-form {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.homework-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.homework-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.homework-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.homework-info {
  flex: 1;
}

.homework-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.homework-desc {
  font-size: 14px;
  color: #606266;
  margin: 0 0 12px 0;
  line-height: 1.5;
}

.homework-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.subject-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.subject-tag.math {
  background: #f0f9ff;
  color: #1890ff;
}

.subject-tag.chinese {
  background: #fff7e6;
  color: #fa8c16;
}

.subject-tag.english {
  background: #f6ffed;
  color: #52c41a;
}

.due-date {
  font-size: 12px;
  color: #909399;
}

.homework-actions {
  display: flex;
  gap: 8px;
}

.photos-preview {
  border-top: 1px solid #ebeef5;
  padding-top: 16px;
}

.photos-preview h4 {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 12px 0;
}

.photos-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
}

.photo-item {
  border: 1px solid #ebeef5;
  border-radius: 6px;
  overflow: hidden;
  background: #fff;
}

.photo-thumbnail {
  width: 100%;
  height: 80px;
  object-fit: cover;
  display: block;
}

.photo-actions {
  padding: 8px;
  display: flex;
  gap: 4px;
}

.photo-actions .el-button {
  flex: 1;
  font-size: 12px;
  padding: 4px 8px;
}

.submit-section {
  text-align: center;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .homework-header {
    flex-direction: column;
    gap: 12px;
  }

  .homework-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .photos-grid {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  }
}
</style>